import axios from 'axios';
import {
    Message
} from "element-ui";
import JSONBIG from 'json-bigint';
axios.defaults.isRetryRequest = false;
axios.defaults.baseURL = 'https://api.niushi.tv/api/index/';
axios.defaults.timeout = 2 * 60 * 1000; // 超时时间
// request拦截器
axios.interceptors.request.use(
    (config) => {
        config.headers['Content-Type'] = 'application/json;charset=UTF-8';
        config.headers['token'] = '';
        return config;
    },
    (error) => {
        // Do something with request error
        Promise.reject(error);
    }
);
axios.defaults.transformResponse = [
    function (data) {
        if (typeof data == 'string') {
            const json = JSONBIG({
                storeAsString: true,
            });
            const res = json.parse(data);
            return res;
        } else {
            return data;
        }
    },
];
// // response 拦截器
axios.interceptors.response.use(
    (response) => {
        if (response.data.code != 1) {
            if (response.data.code == 401) {} else {
                if (response.data.code != 400) {
                    response.data.msg ? Message.warning(response.data.msg) : '';
                }
            }
        }
        axios.defaults.isRetryRequest = false;
        return response;
    },
    (error) => {
        if (JSON.stringify(error).indexOf('Error: timeout of') != -1) {
            Message.warning('请求超时，请刷新重试！');
        } else {
            Message.error('网络慢，请刷新重试！');
        }
        return Promise.reject(error);
    }
);
// axios 请求方法封装
export const post = (url, data) => {
    return new Promise((resolve, reject) => {
        axios
            .post(url, data)
            .then((res) => {
                resolve(res.data);
            })
            .catch((err) => {
                reject(err);
            });
    });
};

export const get = (url, data = {}) => {
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                params: data,
            })
            .then((res) => {
                resolve(res.data);
            })
            .catch((err) => {
                reject(err);
            });
    });
};